<template>
    <div class="user-center">
        <!-- 头部导航 -->
        <header class="header">
            <div class="container">
                <div class="logo">
                    <router-link to="/" class="logo-link">
                        <h1>伟邦人才信息网</h1>
                    </router-link>
                </div>
                <nav class="nav">
                    <router-link to="/" class="nav-item">首页</router-link>
                    <router-link to="/user" class="nav-item active">个人中心</router-link>
                    <router-link to="/admin" v-if="userStore.isAdmin" class="nav-item">管理后台</router-link>
                    <el-button @click="logout" type="text">退出</el-button>
                </nav>
            </div>
        </header>

        <!-- 主要内容 -->
        <div class="main-content">
            <div class="container">
                <div class="user-layout">
                    <!-- 左侧用户信息 -->
                    <div class="user-sidebar">
                        <div class="user-card">
                            <div class="user-avatar">
                                <el-icon><User /></el-icon>
                            </div>
                            <div class="user-info">
                                <h3>{{ userStore.user?.nickName }}</h3>
                                <p class="user-role">{{ userStore.user?.userRole === 'admin' ? '管理员' : '业务员' }}</p>
                                <p class="user-username">{{ userStore.user?.username }}</p>
                            </div>

                            <div class="user-stats">
                                <div class="stat-item">
                                    <span class="stat-number">{{ myCustomerCount }}</span>
                                    <span class="stat-label">我的客户</span>
                                </div>
                                <div class="stat-item">
                                    <span class="stat-number">{{ myShareCount }}</span>
                                    <span class="stat-label">分享次数</span>
                                </div>
                            </div>
                        </div>

                        <div class="contact-card">
                            <h4>联系方式</h4>
                            <div class="contact-item">
                                <el-icon><Phone /></el-icon>
                                <span>{{ userStore.user?.phonenumber }}</span>
                            </div>
                            <!--<div class="contact-item">-->
                            <!--<el-icon><ChatDotRound /></el-icon>-->
                            <!--<span>{{ userStore.user?.wechat }}</span>-->
                            <!--</div>-->
                            <!--<div class="contact-item">-->
                            <!--<el-icon><Message /></el-icon>-->
                            <!--<span>{{ userStore.user?.email }}</span>-->
                            <!--</div>-->
                        </div>
                    </div>

                    <!-- 右侧内容区域 -->
                    <div class="user-main">
                        <!-- 标签页 -->
                        <el-tabs v-model="activeTab" @tab-change="tabChange" class="user-tabs">
                            <el-tab-pane label="我的客户" name="customers">
                                <div class="tab-content">
                                    <div class="content-header">
                                        <h3>我的客户列表</h3>
                                        <!--<el-button type="primary" @click="exportCustomers">-->
                                        <!--<el-icon><Download /></el-icon>-->
                                        <!--导出客户-->
                                        <!--</el-button>-->
                                    </div>

                                    <el-table :data="myCustomers" style="width: 100%">
                                        <el-table-column prop="customerName" label="客户姓名" width="120" />
                                        <el-table-column prop="phone" label="手机号" width="130" />
                                        <el-table-column prop="wechat" label="微信号" width="120" />
                                        <el-table-column prop="email" label="邮箱" width="180" />
                                        <el-table-column prop="experience" label="工作经验" width="100" />
                                        <el-table-column prop="expectedSalary" label="期望薪资" width="100" />
                                        <el-table-column prop="registerTime" label="登记时间" width="160" />
                                        <el-table-column prop="status" label="状态" width="100">
                                            <template #default="scope">
                                                <el-tag :type="getStatusType(scope.row.status)">
                                                    {{ getStatusText(scope.row.status) }}
                                                </el-tag>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="操作" width="150">
                                            <template #default="scope">
                                                <el-button size="small" @click="contactCustomer(scope.row)">
                                                    联系客户
                                                </el-button>
                                                <el-button size="small" type="success" @click="updateStatus(scope.row, 'contacted')">
                                                    已联系
                                                </el-button>
                                                <el-button size="small" type="success" @click="updateStatus(scope.row, 'rejected')">
                                                    已拒绝
                                                </el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <el-pagination
                                            v-if="customersPagination.total > 0"
                                            @size-change="handleCustomersSizeChange"
                                            @current-change="handleCustomersPageChange"
                                            :current-page="customersPagination.pageNum"
                                            :page-sizes="[10, 20, 50, 100]"
                                            :page-size="customersPagination.pageSize"
                                            layout="total, sizes, prev, pager, next"
                                            :total="customersPagination.total"
                                    />
                                </div>
                            </el-tab-pane>

                            <el-tab-pane label="分享统计" name="statistics">
                                <div class="tab-content">
                                    <div class="stats-grid">
                                        <div class="stat-card">
                                            <div class="stat-icon">
                                                <el-icon><Share /></el-icon>
                                            </div>
                                            <div class="stat-content">
                                                <h4>总分享次数</h4>
                                                <p class="stat-number">{{ totalShareCount }}</p>
                                            </div>
                                        </div>

                                        <div class="stat-card">
                                            <div class="stat-icon">
                                                <el-icon><User /></el-icon>
                                            </div>
                                            <div class="stat-content">
                                                <h4>总客户数</h4>
                                                <p class="stat-number">{{ totalCustomerCount }}</p>
                                            </div>
                                        </div>

                                        <div class="stat-card">
                                            <div class="stat-icon">
                                                <el-icon><TrendCharts /></el-icon>
                                            </div>
                                            <div class="stat-content">
                                                <h4>转化率</h4>
                                                <p class="stat-number">{{ conversionRate }}%</p>
                                            </div>
                                        </div>

                                        <div class="stat-card">
                                            <div class="stat-icon">
                                                <el-icon><Calendar /></el-icon>
                                            </div>
                                            <div class="stat-content">
                                                <h4>本月新增</h4>
                                                <p class="stat-number">{{ monthlyNewCount }}</p>
                                            </div>
                                        </div>
                                    </div>

                                    <!--<div class="chart-section">-->
                                    <!--<h4>分享趋势</h4>-->
                                    <!--<div class="chart-placeholder">-->
                                    <!--<p>这里可以集成图表库显示分享趋势</p>-->
                                    <!--</div>-->
                                    <!--</div>-->
                                </div>
                            </el-tab-pane>

                            <!--<el-tab-pane label="个人设置" name="settings">-->
                            <!--<div class="tab-content">-->
                            <!--<el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">-->
                            <!--<el-form-item label="姓名" prop="name">-->
                            <!--<el-input v-model="userForm.name" />-->
                            <!--</el-form-item>-->
                            <!--<el-form-item label="手机号" prop="phone">-->
                            <!--<el-input v-model="userForm.phone" />-->
                            <!--</el-form-item>-->
                            <!--<el-form-item label="微信号" prop="wechat">-->
                            <!--<el-input v-model="userForm.wechat" />-->
                            <!--</el-form-item>-->
                            <!--<el-form-item label="邮箱" prop="email">-->
                            <!--<el-input v-model="userForm.email" />-->
                            <!--</el-form-item>-->
                            <!--<el-form-item>-->
                            <!--<el-button type="primary" @click="updateProfile">保存修改</el-button>-->
                            <!--</el-form-item>-->
                            <!--</el-form>-->
                            <!--</div>-->
                            <!--</el-tab-pane>-->
                        </el-tabs>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { useUserStore } from '@/stores/user'
  import { useJobsStore } from '@/stores/jobs'
  import { mockCustomerRegistrations } from '@/mock/data'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { customersAdd, getCusomer, cusomerList,cusomerUpdate, cusomerListMy,salesmanStatistic} from "@/api/system"

  const router = useRouter()
  const userStore = useUserStore()
  const jobsStore = useJobsStore()

  const activeTab = ref('customers')
  const userFormRef = ref()

  // 用户表单
  const userForm = ref({
      name: userStore.user?.nickName || '',
    phone: userStore.user?.phonenumber || ''
  })

  const userRules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    wechat: [{ required: true, message: '请输入微信号', trigger: 'blur' }],
    email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
  }

  // 我的客户列表
  //const myCustomers = computed(() => {
  //  if (!userStore.user) return []
  //  return jobsStore.getCustomerRegistrationsByUserId(userStore.user.id)
  //})

  const myCustomers = ref([])

  const customersPagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
  })

  const handleCustomersSizeChange = (size) => {
    customersPagination.value.pageSize = size
    customersPagination.value.pageNum = 1
    getCustomersListAll()
  }
  const handleCustomersPageChange = (page) => {
    customersPagination.value.pageNum = page
    getCustomersListAll()
  }

  const getCustomersListAll = async () => {
    try {
      const userInfo = await cusomerListMy({
        pageNum: customersPagination.value.pageNum,
        pageSize: customersPagination.value.pageSize
      })
      myCustomers.value = userInfo.rows || []
      customersPagination.value.total = userInfo.total || 0
    } catch (error) {
      console.error('获取客户列表失败:', error)
      ElMessage.error('获取客户列表失败')
    }
  }

  // 我的客户数量
  const myCustomerCount = computed(() => {
    return customersPagination.value.total
  })

  // 我的分享次数
  const myShareCount = computed(() => {
    return customersPagination.value.total
  })

  // 统计数据
  const totalShareCount = ref(0)
  const totalCustomerCount = ref(0)
  const conversionRate = ref(0)
  const monthlyNewCount = ref(0)

  // 初始化数据
  onMounted(() => {
    // 初始化客户数据
//  jobsStore.customerRegistrations = mockCustomerRegistrations
    getCustomersListAll()
  })

  // 获取状态类型
  const getStatusType = (status) => {
    const statusMap = {
      pending: 'warning',
      contacted: 'success',
      rejected: 'danger'
    }
    return statusMap[status] || 'info'
  }

  // 获取状态文本
  const getStatusText = (status) => {
    const statusMap = {
      pending: '待联系',
      contacted: '已联系',
      rejected: '已拒绝'
    }
    return statusMap[status] || '未知'
  }

  // 联系客户
  const contactCustomer = async (obj) => {
    const customer =  await getCusomer(obj.customerId)
    ElMessageBox.alert(
      `客户信息：\n姓名：${obj.customerName}\n手机：${obj.phone}\n微信：${obj.wechat}\n邮箱：${obj.email}`,
      '客户联系方式',
      {
        confirmButtonText: '确定'
      }
    )
  }

  // 更新客户状态
  const updateStatus = async (customer, status) => {
    await cusomerUpdate(customer.customerId, { status })
    customer.status = status
    ElMessage.success('状态更新成功')
    getCustomersListAll()
  }

  // 业务员排行
  const getSalesmanStatistic = async () => {
    try {
      const res = await salesmanStatistic()
      totalShareCount.value = res.data?.totalShareCount || 0
      totalCustomerCount.value = res.data?.totalCustomerCount || 0
      conversionRate.value = res.data?.conversionRate || 0
      monthlyNewCount.value = res.data?.monthlyNewCount || 0
    } catch (error) {
      console.error('获取业务员排行失败:', error)
      ElMessage.error('获取业务员排行失败')
    }
  }
  const tabChange = (pageName) => {
    if(pageName == 'statistics'){
      getSalesmanStatistic()
    }
  }
  // 导出客户
  const exportCustomers = () => {
    ElMessage.success('客户数据导出成功')
  }

  // 更新个人信息
  const updateProfile = async () => {
    try {
      await userFormRef.value.validate()

      // 更新用户信息
      userStore.user = {
        ...userStore.user,
        ...userForm.value
      }

      ElMessage.success('个人信息更新成功')
    } catch (error) {
      ElMessage.error('请完善个人信息')
    }
  }

  // 退出登录
  const logout = () => {
    userStore.logout()
    router.push('/')
    ElMessage.success('已退出登录')
  }
</script>

<style scoped>
    .user-center {
        min-height: 100vh;
        background-color: #f5f5f5;
    }

    .container {
        margin: 0 auto;
        padding: 0 20px;
    }

    /* 头部样式 */
    .header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px 0;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .header .container {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .logo-link {
        color: white;
        text-decoration: none;
    }

    .logo h1 {
        margin: 0;
        font-size: 24px;
        font-weight: bold;
    }

    .nav {
        display: flex;
        align-items: center;
        gap: 20px;
    }

    .nav-item {
        color: white;
        text-decoration: none;
        padding: 8px 16px;
        border-radius: 4px;
        transition: background-color 0.3s;
    }

    .nav-item:hover,
    .nav-item.active {
        background-color: rgba(255,255,255,0.2);
    }

    /* 主要内容 */
    .main-content {
        padding: 40px 0;
    }

    .user-layout {
        display: grid;
        grid-template-columns: 300px 1fr;
        gap: 30px;
    }

    /* 侧边栏 */
    .user-sidebar {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .user-card,
    .contact-card {
        background: white;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .user-avatar {
        width: 80px;
        height: 80px;
        background: #667eea;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 30px;
        margin: 0 auto 15px;
    }

    .user-info {
        text-align: center;
        margin-bottom: 20px;
    }

    .user-info h3 {
        color: #333;
        margin: 0 0 5px 0;
    }

    .user-role {
        color: #667eea;
        margin: 0 0 5px 0;
        font-weight: bold;
    }

    .user-username {
        color: #666;
        margin: 0;
        font-size: 14px;
    }

    .user-stats {
        display: flex;
        gap: 20px;
    }

    .stat-item {
        text-align: center;
        flex: 1;
    }

    .stat-number {
        display: block;
        font-size: 20px;
        font-weight: bold;
        color: #667eea;
    }

    .stat-label {
        font-size: 12px;
        color: #666;
    }

    .contact-card h4 {
        color: #333;
        margin: 0 0 15px 0;
    }

    .contact-item {
        display: flex;
        align-items: center;
        gap: 10px;
        color: #666;
        margin-bottom: 10px;
        font-size: 14px;
    }

    /* 主内容区域 */
    .user-main {
        background: white;
        border-radius: 8px;
        padding: 30px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .user-tabs {
        height: 100%;
    }

    .tab-content {
        padding: 20px 0;
    }

    .content-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .content-header h3 {
        margin: 0;
        color: #333;
    }

    /* 统计卡片 */
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .stat-card {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .stat-icon {
        width: 50px;
        height: 50px;
        background: #667eea;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 20px;
    }

    .stat-content h4 {
        margin: 0 0 5px 0;
        color: #666;
        font-size: 14px;
    }

    .stat-content .stat-number {
        margin: 0;
        font-size: 24px;
        font-weight: bold;
        color: #333;
    }

    .chart-section {
        margin-top: 30px;
    }

    .chart-section h4 {
        margin: 0 0 15px 0;
        color: #333;
    }

    .chart-placeholder {
        background: #f8f9fa;
        border: 2px dashed #ddd;
        border-radius: 8px;
        padding: 60px 20px;
        text-align: center;
        color: #666;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .container {
            padding: 0 15px;
        }

        .header .container {
            flex-direction: column;
            gap: 15px;
        }

        .nav {
            flex-wrap: wrap;
            justify-content: center;
        }

        .user-layout {
            grid-template-columns: 1fr;
        }

        .stats-grid {
            grid-template-columns: 1fr;
        }

        .content-header {
            flex-direction: column;
            gap: 15px;
            align-items: flex-start;
        }
    }
</style> 